<template>
  <div class="deploy-manager">
    <el-container>
      <!-- 头部 -->
      <el-header class="header">
        <div class="header-content">
          <h1>🚀 微前端部署管理</h1>
          <div class="header-actions">
            <el-button type="primary" @click="refreshStatus">
              <el-icon><Refresh /></el-icon>
              刷新状态
            </el-button>
            <el-button type="success" @click="deployAll">
              <el-icon><Upload /></el-icon>
              批量部署
            </el-button>
          </div>
        </div>
      </el-header>

      <!-- 主要内容 -->
      <el-main class="main-content">
        <!-- 应用列表 -->
        <div class="apps-grid">
          <el-card 
            v-for="app in apps" 
            :key="app.name"
            class="app-card"
            :class="{ 'deploying': app.status === 'deploying' }"
          >
            <template #header>
              <div class="card-header">
                <div class="app-info">
                  <h3>{{ app.displayName }}</h3>
                  <el-tag 
                    :type="getStatusType(app.status)"
                    size="small"
                  >
                    {{ getStatusText(app.status) }}
                  </el-tag>
                </div>
                <div class="app-port">
                  端口: {{ app.port }}
                </div>
              </div>
            </template>

            <div class="app-content">
              <!-- 应用状态 -->
              <div class="status-info">
                <div class="status-item">
                  <span class="label">版本:</span>
                  <span class="value">{{ app.version || 'N/A' }}</span>
                </div>
                <div class="status-item">
                  <span class="label">环境:</span>
                  <span class="value">{{ app.environment || 'N/A' }}</span>
                </div>
                <div class="status-item">
                  <span class="label">最后部署:</span>
                  <span class="value">{{ app.lastDeploy || 'N/A' }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="app-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  :loading="app.status === 'deploying'"
                  @click="deployApp(app)"
                >
                  <el-icon><Upload /></el-icon>
                  部署
                </el-button>
                
                <el-button 
                  type="success" 
                  size="small"
                  @click="viewLogs(app)"
                >
                  <el-icon><Document /></el-icon>
                  日志
                </el-button>
                
                <el-button 
                  type="info" 
                  size="small"
                  @click="viewApp(app)"
                >
                  <el-icon><View /></el-icon>
                  访问
                </el-button>
                
                <el-button 
                  type="warning" 
                  size="small"
                  @click="rollbackApp(app)"
                >
                  <el-icon><RefreshLeft /></el-icon>
                  回滚
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 部署进度 -->
        <el-card v-if="deploymentProgress.show" class="progress-card">
          <template #header>
            <h3>部署进度</h3>
          </template>
          <div class="progress-content">
            <el-progress 
              :percentage="deploymentProgress.percentage"
              :status="deploymentProgress.status"
            />
            <p class="progress-text">{{ deploymentProgress.text }}</p>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 部署日志对话框 -->
    <el-dialog
      v-model="logDialog.visible"
      :title="`${logDialog.appName} - 部署日志`"
      width="80%"
    >
      <div class="log-container">
        <div class="log-content" ref="logContent">
          <div 
            v-for="(log, index) in logDialog.logs" 
            :key="index"
            class="log-line"
            :class="log.type"
          >
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Upload,
  Document,
  View,
  RefreshLeft
} from '@element-plus/icons-vue'

// 应用配置
const apps = ref([
  {
    name: 'login-app',
    displayName: '登录应用',
    port: 3003,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  },
  {
    name: 'system-app',
    displayName: '系统管理',
    port: 3005,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  },
  {
    name: 'dashboard-app',
    displayName: '仪表板',
    port: 3007,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  },
  {
    name: 'tenant-app',
    displayName: '租户管理',
    port: 3009,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  },
  {
    name: 'tool-app',
    displayName: '工具应用',
    port: 3006,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  },
  {
    name: 'workflow-app',
    displayName: '工作流',
    port: 3008,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  },
  {
    name: 'monitor-app',
    displayName: '监控应用',
    port: 3010,
    status: 'stopped',
    version: '',
    environment: '',
    lastDeploy: ''
  }
])

// 部署进度
const deploymentProgress = reactive({
  show: false,
  percentage: 0,
  status: 'success',
  text: ''
})

// 日志对话框
const logDialog = reactive({
  visible: false,
  appName: '',
  logs: [] as Array<{ time: string, message: string, type: string }>
})

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    running: 'success',
    stopped: 'info',
    deploying: 'warning',
    error: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    running: '运行中',
    stopped: '已停止',
    deploying: '部署中',
    error: '错误'
  }
  return statusMap[status] || '未知'
}

// 部署单个应用
const deployApp = async (app: any) => {
  try {
    app.status = 'deploying'
    deploymentProgress.show = true
    deploymentProgress.percentage = 0
    deploymentProgress.text = `开始部署 ${app.displayName}...`
    
    // 模拟部署过程
    for (let i = 0; i < 6; i++) {
      const steps = ['检查依赖', '构建应用', '构建镜像', '推送镜像', '部署服务', '健康检查']
      deploymentProgress.text = `正在执行: ${steps[i]}`
      deploymentProgress.percentage = ((i + 1) / 6) * 100
      
      await new Promise(resolve => setTimeout(resolve, 1000))
    }
    
    // 部署完成
    app.status = 'running'
    app.version = 'v1.0.0'
    app.environment = 'production'
    app.lastDeploy = new Date().toLocaleString()
    
    deploymentProgress.status = 'success'
    deploymentProgress.text = `${app.displayName} 部署成功！`
    
    ElMessage.success(`${app.displayName} 部署成功！`)
    
    // 3秒后隐藏进度
    setTimeout(() => {
      deploymentProgress.show = false
    }, 3000)
    
  } catch (error) {
    app.status = 'error'
    deploymentProgress.status = 'exception'
    deploymentProgress.text = `${app.displayName} 部署失败！`
    ElMessage.error(`${app.displayName} 部署失败！`)
  }
}

// 批量部署
const deployAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要批量部署所有应用吗？这可能需要较长时间。',
      '确认部署',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    for (const app of apps.value) {
      if (app.status !== 'running') {
        await deployApp(app)
        await new Promise(resolve => setTimeout(resolve, 2000))
      }
    }
    
    ElMessage.success('所有应用部署完成！')
    
  } catch (error) {
    ElMessage.info('已取消批量部署')
  }
}

// 查看日志
const viewLogs = (app: any) => {
  logDialog.visible = true
  logDialog.appName = app.displayName
  logDialog.logs = [
    { time: '14:30:15', message: '开始部署应用', type: 'info' },
    { time: '14:30:16', message: '检查依赖...', type: 'info' },
    { time: '14:30:18', message: '依赖检查通过', type: 'success' },
    { time: '14:30:19', message: '开始构建应用...', type: 'info' },
    { time: '14:30:25', message: '应用构建完成', type: 'success' },
    { time: '14:30:26', message: '开始构建Docker镜像...', type: 'info' },
    { time: '14:30:35', message: 'Docker镜像构建完成', type: 'success' },
    { time: '14:30:36', message: '推送镜像到仓库...', type: 'info' },
    { time: '14:30:42', message: '镜像推送完成', type: 'success' },
    { time: '14:30:43', message: '开始部署服务...', type: 'info' },
    { time: '14:30:48', message: '服务部署完成', type: 'success' },
    { time: '14:30:49', message: '执行健康检查...', type: 'info' },
    { time: '14:30:52', message: '健康检查通过', type: 'success' },
    { time: '14:30:53', message: '部署完成！', type: 'success' }
  ]
}

// 访问应用
const viewApp = (app: any) => {
  const url = `http://localhost:${app.port}`
  window.open(url, '_blank')
}

// 回滚应用
const rollbackApp = async (app: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要回滚 ${app.displayName} 到上一个版本吗？`,
      '确认回滚',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    app.status = 'deploying'
    deploymentProgress.show = true
    deploymentProgress.text = `正在回滚 ${app.displayName}...`
    
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    app.status = 'running'
    app.version = 'v0.9.0'
    deploymentProgress.show = false
    
    ElMessage.success(`${app.displayName} 回滚成功！`)
    
  } catch (error) {
    ElMessage.info('已取消回滚')
  }
}

// 刷新状态
const refreshStatus = async () => {
  ElMessage.info('正在刷新应用状态...')
  
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  apps.value.forEach(app => {
    if (Math.random() > 0.5) {
      app.status = 'running'
      app.version = 'v1.0.0'
      app.environment = 'production'
      app.lastDeploy = new Date().toLocaleString()
    }
  })
  
  ElMessage.success('状态刷新完成！')
}

// 组件挂载
onMounted(() => {
  refreshStatus()
})
</script>

<style scoped>
.deploy-manager {
  height: 100vh;
  background: #f5f5f5;
}

.header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.main-content {
  padding: 20px;
}

.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.app-card {
  transition: all 0.3s ease;
}

.app-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-card.deploying {
  border-color: #e6a23c;
  background: linear-gradient(135deg, #fff9e6 0%, #ffffff 100%);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.app-port {
  color: #909399;
  font-size: 14px;
}

.status-info {
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.status-item .label {
  color: #909399;
}

.status-item .value {
  color: #303133;
  font-weight: 500;
}

.app-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.progress-card {
  margin-top: 20px;
}

.progress-content {
  text-align: center;
}

.progress-text {
  margin: 16px 0;
  color: #606266;
  font-size: 16px;
}

.log-container {
  height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.log-content {
  height: 100%;
  overflow-y: auto;
  padding: 10px;
  background: #1e1e1e;
  color: #fff;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.log-line {
  margin-bottom: 4px;
  display: flex;
  gap: 10px;
}

.log-time {
  color: #888;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.log-line.info .log-message {
  color: #409eff;
}

.log-line.success .log-message {
  color: #67c23a;
}

.log-line.error .log-message {
  color: #f56c6c;
}

.log-line.warning .log-message {
  color: #e6a23c;
}
</style>
